package com.shelpe.services.auth.configuration;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.alibaba.druid.pool.DruidDataSource;
import com.shelpe.services.auth.configuration.DBConfiguration.SandboxDataSourceProperties;

import lombok.Data;

@Configuration
@EnableJpaRepositories(basePackages="com.shelpe.services.auth.repository")
@EnableConfigurationProperties(SandboxDataSourceProperties.class)
public class DBConfiguration {

	@Bean
	@Profile("dev")
    public DataSource sandboxDataSource(DataSourceProperties props, SandboxDataSourceProperties sandbox) {
		DruidDataSource ds = new DruidDataSource();
		if(props != null){
			ds.setDriverClassName(props.getDriverClassName());
			ds.setUrl(sandbox.getUrl());
			ds.setUsername(sandbox.getUsername());
			ds.setPassword(sandbox.getPassword());
		}
        return ds;
    }

	@Bean
	@Primary
    public DataSource dataSource(DataSourceProperties props) {
		DruidDataSource ds = new DruidDataSource();
		if(props != null){
			ds.setDriverClassName(props.getDriverClassName());
			ds.setUrl(props.getUrl());
			ds.setUsername(props.getUsername());
			ds.setPassword(props.getPassword());
		}
        return ds;
    }
	
	@Data
	@ConfigurationProperties(prefix = "sandbox.datasource")
	public static class SandboxDataSourceProperties{
		/**
		 * JDBC url of the database.
		 */
		private String url;

		/**
		 * Login user of the database.
		 */
		private String username;

		/**
		 * Login password of the database.
		 */
		private String password;
	}
}
